// #ifdef H5
var jweixin = require('jweixin-module');
// #endif
import {
	_createOrder,
	_recharge
} from '@/api/mall.js'

const defaultOptions = {
	// #ifdef MP-WEIXIN
	orderOrigin: 1,
	// #endif
	// #ifdef H5
	orderOrigin: 2,
	// #endif
	remarkByClient: '',
	point: 0,
	cityName: '',
	provinceName: '',
	areaName: '',
	expressAddress: '',
	expressTelephone: '',
	expresssUserName: ''
}

function mergeOptions(defaultOptions, instanceOptions) {
	const OPTIONS_KEY_LIST = ['orderOrigin', 'point', 'cityName', 'provinceName', 'areaName', 'expressAddress',
		'expressTelephone', 'expresssUserName'
	];
	const OPTIONS_ALL_KEY_LIST = [...OPTIONS_KEY_LIST];
	const ARGS_ALL_KEY_LIST = [...new Set([...Object.keys(instanceOptions), ...Object.keys(defaultOptions)])]
	const REMAINDER_KEY_LIST = ARGS_ALL_KEY_LIST.filter(key => !OPTIONS_ALL_KEY_LIST.includes(key));
	let newOptions = {};
	OPTIONS_ALL_KEY_LIST.forEach(item => {
		const val = instanceOptions[item] || defaultOptions[item];

		if (typeof val == 'boolean') {
			newOptions[item] = instanceOptions[item] == null ? defaultOptions[item] : instanceOptions[item];
		} else if (typeof val == 'number') {
			newOptions[item] = val || 0;
		} else {
			newOptions[item] = val || '';
		}
	})
	REMAINDER_KEY_LIST.forEach(item => {
		const val = instanceOptions[item];
		if (typeof val == 'boolean') {
			newOptions[item] = val;
		} else if (typeof val == 'number') {
			newOptions[item] = val || 0;
		} else {
			newOptions[item] = val || '';
		}
	})
	return newOptions;
}

async function createOrder(options) {
	if (!options) {
		options = {};
	}
	const newOptions = mergeOptions(defaultOptions, options);
	var result = await _createOrder(newOptions);
	return result;
}

async function _pay(data, callback_succ_func, callback_error_func) {
	var orderInfo = await createOrder(data);
	await onlyPay(orderInfo, callback_succ_func, callback_error_func);
}


async function _onlyPay(data, callback_succ_func, callback_error_func) {
	// #ifdef MP-WEIXIN
	uni.requestPayment({
		provider: 'wxpay',
		timeStamp: data.timeStamp,
		nonceStr: data.nonceStr,
		package: data.package,
		signType: data.signType,
		paySign: data.paySign,
		success() {
			uni.showToast({
				title: '支付成功',
				mask: true,
				duration: 1000,
				success() {
					if (callback_succ_func && typeof callback_succ_func == "function") {
						setTimeout(function() {
							callback_succ_func();
						}, 1000)
					}
				}
			})
		},
		fail() {
			if (callback_error_func && typeof callback_error_func == "function") {
				callback_error_func()
			}
		}
	});
	// #endif
	// #ifdef H5
	wxPay(data, callback_succ_func, callback_error_func)
	// #endif
}



async function _rechage(data, callback_succ_func, callback_error_func) {
	// #ifdef MP-WEIXIN
	data.paymentMethod = 1;
	// #endif
	// #ifdef H5
	data.paymentMethod = 2;
	// #endif
	var result = await _recharge(data);
	// #ifdef MP-WEIXIN
	uni.requestPayment({
		provider: 'wxpay',
		timeStamp: result.timeStamp,
		nonceStr: result.nonceStr,
		package: result.package,
		signType: result.signType,
		paySign: result.paySign,
		success() {
			uni.showToast({
				title: '支付成功',
				mask: true,
				duration: 1000,
				success() {
					if (callback_succ_func && typeof callback_succ_func == "function") {
						setTimeout(function() {
							callback_succ_func();
						}, 1000)
					}
				}
			})
		},
		fail() {
			if (callback_error_func && typeof callback_error_func == "function") {
				callback_error_func()
			}
		}
	});
	// #endif
	// #ifdef H5
	wxPay(result, callback_succ_func, callback_error_func)
	// #endif
}

// #ifdef H5
function isWechat() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}

function jsApiCall(data, callback_succ_func, callback_error_func) {
	//使用原生的，避免初始化appid问题  
	WeixinJSBridge.invoke('getBrandWCPayRequest', {
			appId: data.appId,
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位  
			package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）  
			signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'  
			paySign: data.paySign, // 支付签名  
		},
		function(res) {
			var msg = res.err_msg ? res.err_msg : res.errMsg;
			//WeixinJSBridge.log(msg);  
			switch (msg) {
				case 'get_brand_wcpay_request:ok': //支付成功时  

					uni.showToast({
						title: '支付成功',
						mask: true,
						duration: 1000,
						success() {
							if (callback_succ_func && typeof callback_succ_func == "function") {
								setTimeout(function() {
									callback_succ_func();
								}, 1000)
							}
						}
					})

					break;
				default: //支付失败时  
					WeixinJSBridge.log('支付失败!' + msg + ',请返回重试.');
					if (callback_error_func && typeof callback_error_func == "function") {
						callback_error_func({
							msg: msg
						});
					}
					break;
			}
		})
}

function wxPay(data, callback_succ_func, callback_error_func) {
	if (!isWechat()) {
		return;
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', jsApiCall);
			document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		}
	} else {
		jsApiCall(data, callback_succ_func, callback_error_func);
	}
}
// #endif


export const pay = _pay;
export const onlyPay = _onlyPay;
export const rechage = _rechage;
